package com.bxd.baodan.adapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.j256.ormlite.dao.Dao;
import com.bxd.baodan.App;
import com.bxd.baodan.R;
import com.bxd.baodan.activity.AdviserActivity;
import com.bxd.baodan.activity.LoginActivity;
import com.bxd.baodan.app.Constant;
import com.bxd.baodan.app.LoginInfo;
import com.bxd.baodan.base.BaseBaseAdapter;
import com.bxd.baodan.db.DBHelper;
import com.bxd.baodan.item.MessageItem;
import com.bxd.baodan.util.DateUtil;
import com.bxd.baodan.util.ImageUtil;
import com.bxd.baodan.util.LogUtil;
import com.tencent.TIMConversationType;
import com.tencent.qcloud.timchat.ui.ChatActivity;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 消息适配器
 */
public class AnswerMessageAdapter extends BaseBaseAdapter<MessageItem> {
    public String[] msgType;

    public AnswerMessageAdapter(Context context, String[] type) {
        super(context, R.drawable.empty_person);
        this.msgType = type;
    }

    class ViewHolder {
        private ImageView ivAvatar;
        private TextView tvName;
        private TextView tvContent;
        private TextView tvAnswerAddress;
        private TextView tvAnswerCompany;
        TextView verify_level;
        TextView chat;
        ImageView verify_icon;
        ImageView msg_isread_icon;
        TextView text_time;
    }

    @Override
    public View getView(final int position, View view) {
        final MessageItem item = getItem(position);

        ViewHolder viewHolder = null;
        // 如果是任务消息，使用另外一个布局
        if (viewHolder == null) {
            viewHolder = new ViewHolder();
            view = inflater.inflate(R.layout.msg_answer_item, null);
            viewHolder.ivAvatar = getImageView(view, R.id.answer_avatar);
            viewHolder.tvName = getTextView(view, R.id.answer_name);
            viewHolder.tvContent = getTextView(view, R.id.answer_content);
            viewHolder.tvAnswerAddress = getTextView(view, R.id.answer_address);
            viewHolder.tvAnswerCompany = getTextView(view, R.id.answer_company);
            viewHolder.verify_level = (TextView) view.findViewById(R.id.verify_level);
            viewHolder.chat = (TextView) view.findViewById(R.id.chat_status);
            viewHolder.verify_icon = (ImageView) view.findViewById(R.id.verify_icon);
            viewHolder.msg_isread_icon = (ImageView) view.findViewById(R.id.msg_isread_icon);
            viewHolder.text_time = (TextView) view.findViewById(R.id.text_time);
            view.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) view.getTag();
        }


        viewHolder.ivAvatar.setImageResource(R.drawable.empty_person);
        viewHolder.ivAvatar.setTag(item.getUserInfo().getU_id());
        ImageUtil.setAvatarToRounderCorner(context, item.getUserInfo().getUe_avatar(),
                viewHolder.ivAvatar, true);
        viewHolder.ivAvatar.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent(context, AdviserActivity.class);
                intent.putExtra("params", item.getA_id());
                context.startActivity(intent);
                ((Activity) context).overridePendingTransition(
                        R.anim.slide_in_right, R.anim.slide_out_left);
            }
        });
        String ue_realname = item.getUserInfo().getUe_realname();
        if (!ue_realname.equals("")) {
            viewHolder.tvName.setText(ue_realname);
        } else {
            viewHolder.tvName.setText(item.getUserInfo().getU_nick());
        }
        viewHolder.tvAnswerAddress.setText(item.getUserInfo().ue_cityName);
        if (item.getUserInfo().getCompanyname().length() >= 10) {
            viewHolder.tvAnswerCompany.setText(item.getUserInfo().getCompanyname().subSequence(0,
                    10)
                    + "...");
        } else {
            viewHolder.tvAnswerCompany.setText(item.getUserInfo().getCompanyname());
        }

        //-------------------------------------------------------------------------------------------------------
        String verify = "";
        int level = item.getUserInfo().ua_title;
        int verColor = R.color.white;
        int drawableLeft = R.color.transparent;


        switch (level) {
            case 0:
                break;
            case 4:
                verify = "保险管家";
                verColor = R.color.guanja;
                drawableLeft = R.drawable.round_corner_yellow;
                break;
            case 2:
                verify = "保险精英";
                verColor = R.color.jingying;
                drawableLeft = R.drawable.round_corner_blue_jingying;
                break;
            case 1:
                verify = "保险达人";
                verColor = R.color.daren;
                drawableLeft = R.drawable.round_corner_green;
                break;
            case 3:
                verify = "保险专家";
                verColor = R.color.zhuanjia;
                drawableLeft = R.drawable.round_corner_red_zhuanjia;
                break;
            default:
                break;
        }

        viewHolder.verify_level.setBackground(context.getResources().getDrawable(drawableLeft));


        viewHolder.verify_level.setText(verify);
        viewHolder.verify_level.setTextColor(context.getResources().getColor(verColor));
        int chatStatus = 1;
        viewHolder.chat.setBackground(context.getResources().getDrawable(chatStatus == 0 ? R.drawable.bg_gray_stroke : R.drawable.round_corner_yellow));
        viewHolder.chat.setCompoundDrawablesWithIntrinsicBounds(context.getResources().getDrawable(chatStatus == 0 ? R.drawable.one_by_one_gray : R.drawable.one_by_one), null, null, null);
        viewHolder.chat.setTextColor(context.getResources().getColor(chatStatus == 0 ? R.color.gray : R.color.yellow_lab));
        viewHolder.chat.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (LoginInfo.getInstance(App.getContext()).isLogin()) {
                    ChatActivity.navToChat(context, getItem(position).getUserInfo().getU_id() + "", TIMConversationType.C2C);
                } else {
                    context.startActivity(new Intent(context, LoginActivity.class));
                    ((Activity) context).overridePendingTransition(R.anim.slide_in_right,
                            R.anim.slide_out_left);
                }
            }
        });

        // TODO: 2017/3/27 身份认证要改
        if (item.getUserInfo().getAgent_mark() != null && item.getUserInfo().getAgent_mark().length() > 0
                && item.getUserInfo().getAgent_mark().contains("6")) {
            viewHolder.verify_icon.setVisibility(View.VISIBLE);
        } else {
            viewHolder.verify_icon.setVisibility(View.GONE);
        }
        viewHolder.tvContent.setText(item.getContent());


        viewHolder.text_time.setText(DateUtil.getTimeStamp(item.getTime()));

        viewHolder.msg_isread_icon.setVisibility(item.isIsread() ? View.GONE : View.VISIBLE);
        return view;
    }

    List<MessageItem> list1 = new ArrayList<>();

    @Override
    public void getData(int page) {

        try {
            if (page == 0) {
                list.clear();
            }
            Dao<MessageItem, ?> dao = DBHelper.getInstance(context).getDao(MessageItem.class);
            list1 = dao.queryBuilder().offset(page * Constant.PAGE_SIZE)
                    .limit(Constant.PAGE_SIZE).
                            orderBy("time", false).where().
                            eq("uid", LoginInfo.getInstance(context).getUser().getU_id()).and().
                            in("type", msgType).query();
            for (MessageItem messageItem : list) {
                messageItem.setNoReadCount(DBHelper.getInstance(context).getNoReadCount(messageItem));
            }
            addAll(list1);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除本条消息
     */
    private void SetCancel(final MessageItem item) {

        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setMessage("您确定要删除本条消息吗?")
                .setTitle("提示")
                .setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                delete(item);
                                dialog.dismiss();
                            }
                        }).setNegativeButton("取消", null).show();
    }

    public void delete(MessageItem item) {
        Dao<MessageItem, ?> dao;
        try {
            dao = DBHelper.getInstance(context).getDao(MessageItem.class);
            int clums = dao.delete(item);
            LogUtil.e("删除消息行数等于" + clums);
            cleanNotificationByMessageItemId(item);
            remove(item);
            setNotift();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void cleanNotificationByMessageItemId(MessageItem item) {
        NotificationManager mNotificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.cancel(item.getId());
    }

    public void setNotift() {
        context.sendBroadcast(new Intent(Constant.ACTION_RECEIVE_AD));
        notifyDataSetChanged();
        // adapter.getData(0);
    }
}